import configparser
import sys

import command
import constants
import utils


def get_config_path() -> str:
    return command.include_command_path(constants.CONFIG_FILE_PATH)


def get_config() -> configparser.ConfigParser:
    return utils.read_properties(get_config_path())


def save_config(config: configparser.ConfigParser):
    path = command.include_command_path(constants.CONFIG_FILE_PATH)
    utils.save_properties(path, config)


def set_config_not_exist(section, key, value):
    path = get_config_path()
    rw_config = utils.read_properties(path)
    rw_config.set(section, key, value)
    utils.save_properties(path, rw_config)


def set_config(section, key, value):
    path = get_config_path()
    rw_config = utils.read_properties(path)
    option = rw_config.has_option(section, key)
    if option:
        rw_config.set(section, key, value)
        utils.save_properties(path, rw_config)
    else:
        print("not exist key : %s" % key)


def print_config():
    g_config = get_config()
    # 遍历所有节
    for section in g_config.sections():
        print(f"[{section}]")

        # 遍历节中的所有键值对
        for key, value in g_config.items(section):
            print(f"{key} = {value}")
        print()


def print_section(section):
    g_config = get_config()
    options = g_config.options(section)
    for option in options:
        print(f"{option} = {g_config.get(section, option)}")


if __name__ == '__main__':
    args = sys.argv
    if len(args) == 1:
        print_config()
        sys.exit()
    if len(args) == 2:
        print_section(args[1])
        sys.exit()
    if len(args) > 3:
        set_config_not_exist(str(args[1]), args[2], args[3])
    else:
        print("Usage: config <section> <key> <value>")
        sys.exit()
